/*=============================================================================
#    The element-comm is a tentative program used to test our ideas.           
#                       Copyright (C)  bgao                                    
#
#     This program is free software; you can redistribute it and/or            
#      modify it under the terms of the GNU General Public License             
#     as published by the Free Software Foundation; either version 2           
#         of the License, or (at your option) any later version.               
#
#     This program is distributed in the hope that it will be useful,          
#    but WITHOUT ANY WARRANTY; without even the implied warranty of           
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the            
#             GNU General Public License for more details.                    
#
#    You should have received a copy of the GNU General Public License        
#     along with this program; if not, write to the Free Software             
#      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,             
#                       MA  02110-1301, USA.                                  
#==============================================================================
# $Id$ 
#
# $Author$ 
#
# $Revision$ 
#
# $Date$ 
#
# Description: 
#
=============================================================================*/
#include "rtos-wsn.h"
#include "AVR/avr-common.h"
#include "led.h"
#include <avr/sleep.h>

extern void adc_init(void);
extern void spi_init(void);
extern void usart0_init(void);
extern void cc2420_io_init(void);

static unsigned long wsn_task_time;

	
void platform_wsn_init(void)
{
	spi_init();
    usart0_init();
	led_io_init();
	cc2420_io_init();
	set_sleep_mode(SLEEP_MODE_IDLE);
    adc_init();
}



/* Timer0 interrupt handler */

void isr_timer0_comp(void)
//ISR(TIMER0_COMP_vect, ISR_BLOCK)
{
	wsn_LeaveCritical();
    wsn_task_time += 320;/*320us*/
    wsn_timer_tick();

}


void wsn_start_timer(void)
{
    /* start timer0 as rtos system timer: TICK = 320us */
    TCNT0 = 0;/*bottom*/ 
    OCR0 = 80;  /* (320us = 80 * 1 /(8MHz/32)) */ /*top*/ 
    TCCR0 = BIT_SET(WGM01) | BIT_SET(CS00) | BIT_SET(CS01);  /* CTC mode, div = 32 *//*set csxx to start  timer*/
    														   
    TIMSK = BIT_SET(OCIE0);    /* Timer0 CTC mde Interrupt Enable */
	
}


uint32 Wsn_TaskSchedTime(void)
{
	return wsn_task_time;
}

inline void wsn_EnterCritical(void)
{	
	cli();
}


inline void wsn_LeaveCritical(void)
{
	sei();
}

void wsn_system_sleep(void)
{
	sleep_enable();
	wsn_LeaveCritical();
	sleep_cpu();
	sleep_disable();
}

